using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace K3Cloud.WebApi.Core.IoC.K3Client
{
    /// <summary>
    /// 控制台错误日志实现（默认实现）
    /// 将错误日志输出到控制台和调试窗口
    /// </summary>
    public class ConsoleErrorLogger : IK3ErrorLogger
    {
        private readonly string _applicationName;
        private readonly bool _includeStackTrace;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="applicationName">应用程序名称</param>
        /// <param name="includeStackTrace">是否包含堆栈跟踪（默认true）</param>
        public ConsoleErrorLogger(string applicationName = "K3CloudApp", bool includeStackTrace = true)
        {
            _applicationName = applicationName;
            _includeStackTrace = includeStackTrace;
        }

        public void LogError(string message, Exception? exception = null, Dictionary<string, object>? context = null)
        {
            var logBuilder = new StringBuilder();
            logBuilder.AppendLine($"[ERROR] [{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] [{_applicationName}]");
            logBuilder.AppendLine($"Message: {message}");

            if (context != null && context.Count > 0)
            {
                logBuilder.AppendLine("Context:");
                foreach (var kvp in context)
                {
                    logBuilder.AppendLine($"  {kvp.Key}: {kvp.Value}");
                }
            }

            if (exception != null)
            {
                logBuilder.AppendLine($"Exception Type: {exception.GetType().FullName}");
                logBuilder.AppendLine($"Exception Message: {exception.Message}");

                if (_includeStackTrace && !string.IsNullOrEmpty(exception.StackTrace))
                {
                    logBuilder.AppendLine("Stack Trace:");
                    logBuilder.AppendLine(exception.StackTrace);
                }

                // 记录内部异常
                if (exception.InnerException != null)
                {
                    logBuilder.AppendLine($"Inner Exception: {exception.InnerException.Message}");
                }
            }

            logBuilder.AppendLine(new string('-', 80));

            var logMessage = logBuilder.ToString();
            Console.Error.WriteLine(logMessage);
            Debug.WriteLine(logMessage);
        }

        public void LogApiError(string apiName, string formId, string errorMessage, Exception? exception = null)
        {
            var context = new Dictionary<string, object>
            {
                { "ApiName", apiName },
                { "FormId", formId }
            };

            LogError($"K3 API调用失败: {errorMessage}", exception, context);
        }

        public void LogQueryError(string entityType, string? queryJson, string errorMessage, Exception? exception = null)
        {
            var context = new Dictionary<string, object>
            {
                { "EntityType", entityType }
            };

            if (!string.IsNullOrEmpty(queryJson))
            {
                // 限制查询JSON长度，避免日志过长
                context["QueryJson"] = queryJson!.Length > 500 
                    ? queryJson.Substring(0, 500) + "..." 
                    : queryJson;
            }

            LogError($"查询失败: {errorMessage}", exception, context);
        }

        public void LogSaveError(string formId, string? dataJson, string errorMessage, Exception? exception = null)
        {
            var context = new Dictionary<string, object>
            {
                { "FormId", formId }
            };

            if (!string.IsNullOrEmpty(dataJson))
            {
                // 限制数据JSON长度
                context["DataJson"] = dataJson!.Length > 500 
                    ? dataJson.Substring(0, 500) + "..." 
                    : dataJson;
            }

            LogError($"保存数据失败: {errorMessage}", exception, context);
        }

        public void LogBatchError(string operation, string formId, int affectedCount, string errorMessage, Exception? exception = null)
        {
            var context = new Dictionary<string, object>
            {
                { "Operation", operation },
                { "FormId", formId },
                { "AffectedCount", affectedCount }
            };

            LogError($"批量操作失败: {errorMessage}", exception, context);
        }

        public void LogCacheError(string cacheKey, string operation, string errorMessage, Exception? exception = null)
        {
            var context = new Dictionary<string, object>
            {
                { "CacheKey", cacheKey },
                { "Operation", operation }
            };

            LogError($"缓存操作失败: {errorMessage}", exception, context);
        }
    }
}
